<template>
  <div
    h-full
    flex="~ col between items-stretch"
    px-16px
    pb-16px
    :style="pageStyle"
    scrollbar-lg
    gap-8px>
    <a-card
      v-if="showPageHeader"
      :body-style="{ padding: '0 24px', height: '100%' }"
      h-48px
      mt-2
      flex-none
      select-none>
      <div h-full flex-between>
        <a-space :size="16">
          <!-- 面包屑 -->
          <a-breadcrumb>
            <template v-for="(item, index) in breadcrumbItems" :key="item.key">
              <!-- 第一项和没有兄弟菜单的项 -->
              <template v-if="index === 0 || item.siblingMenuItems.length === 0">
                <a-breadcrumb-item>
                  <component :is="item.icon" />
                  {{ item.label }}
                </a-breadcrumb-item>
              </template>
              <!-- 其他项 -->
              <template v-else>
                <a-breadcrumb-item>
                  {{ item.label }}
                  <template #overlay>
                    <a-menu :items="item.siblingMenuItems" @click="handleMenuClick" />
                  </template>
                </a-breadcrumb-item>
              </template>
            </template>
          </a-breadcrumb>
        </a-space>
        <a-space>
          <div :ref="setToolsRef"></div>
          <!-- 返回上级 -->
          <template v-if="showBackBtn">
            <a-button @click="handleBackBtnClick">返回上一级</a-button>
          </template>
        </a-space>
      </div>
    </a-card>

    <main flex-auto :style="mainStyle">
      <!-- 卡片包裹页 -->
      <a-card v-if="hasCardWrapper" h-full :body-style="{ height: '100%', padding: '0px' }">
        <RouterView @set-back-route="setBackRoute" />
      </a-card>

      <!-- 非卡片包裹页 -->
      <RouterView v-else @set-back-route="setBackRoute" />
    </main>
  </div>
</template>

<script setup lang="ts">
import { iconifyToAntdvIconVNode } from '@ykst/shared';
import { type RouteLocationRaw, type RouteRecordName } from 'vue-router/auto';
import { type RouteNamedMap } from 'vue-router/auto/routes';
import { handleMenuClick, getMenuItemsByRoutes } from '@/utils/router/menu';
import { useCompanyPageTools } from '@/stores/ui/useCompanyPageTools';

const router = useRouter();

/** 页面样式 */
const pageStyle = computed(() => {
  const coverStyle = router.currentRoute.value.meta?.layoutCoverStyle ?? {};
  return {
    ...{
      overflow: router.currentRoute.value.meta.layoutPageScroll ? 'auto' : 'hidden',
      paddingTop: showPageHeader.value ? '0px' : '16px',
    },
    ...coverStyle,
  };
});

/** 是否显示页面头 */
const showPageHeader = computed(() => !router.currentRoute.value.meta?.layoutHiddenPageHeader);

/** 是否有卡片包裹 */
const hasCardWrapper = computed(() => router.currentRoute.value.meta?.layoutHasCardWrapper);

/** 非卡片主体样式 */
const mainStyle = computed(() => {
  return {
    // 当未开启页面滚动时，主体内容超出高度时，需要修复
    overflow: router.currentRoute.value.meta.layoutPageScroll ? 'initial' : 'hidden',
  };
});

/** 面包屑 */
const breadcrumbItems = computed(() => {
  return router.currentRoute.value.matched
    .filter(item => item?.name)
    .slice(1)
    .map((item, index, arr) => {
      return {
        label: item.meta?.title ?? '未命名',
        key: item.name,
        icon: item.meta?.icon ? iconifyToAntdvIconVNode(item.meta.icon) : undefined,
        // 兄弟路由菜单
        siblingMenuItems:
          index > 0
            ? getBreadcrumbSiblingMenuItems(
                item.name as RouteRecordName,
                arr[index - 1].name as RouteRecordName,
              )
            : [],
      };
    });
});

/** 获取面包屑兄弟菜单 */
const getBreadcrumbSiblingMenuItems = (
  routeName: RouteRecordName,
  parentRouteName: RouteRecordName,
) => {
  const parentRoute = router.getRoutes().find(t => t.name === parentRouteName);
  return getMenuItemsByRoutes(parentRoute?.children ?? []).filter(t => t?.key !== routeName);
};

/** 是否显示返回按钮 */
const showBackBtn = computed(() => router.currentRoute.value.meta?.showGoBackBtn);

/** 返回路由映射 */
const backRouteMap = reactive<Partial<Record<keyof RouteNamedMap, RouteLocationRaw>>>({});
/** 设置返回路由 */
const setBackRoute = (_route?: RouteLocationRaw) => {
  _route && (backRouteMap[router.currentRoute.value.name] = _route);
};

/** 点击返回按钮 */
const handleBackBtnClick = () => {
  if (router.currentRoute.value?.name && backRouteMap?.[router.currentRoute.value.name]) {
    // 存在通过事件设置的返回路由
    routerPush(backRouteMap[router.currentRoute.value.name] as RouteLocationRaw);
  } else if (router.currentRoute.value.meta?.parentRoutePath) {
    // 存在父路由路径
    routerPush(router.currentRoute.value.meta.parentRoutePath as string);
  } else {
    // 默认
    router.back();
  }
};

/** 工具条的ref */
const { setToolsRef } = useCompanyPageTools();
</script>

<style scoped></style>
